package com.tingyuge.base.thread.wang.lock;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by xiaodao
 * date: 2019/12/18
 */
public class RwLock {

    private final static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);
    private final static Lock readLock = readWriteLock.readLock();
    private final static Lock writeLock = readWriteLock.writeLock();


    private static final List<Long> data = new ArrayList<>();

    public static  void write(){
        try {
            writeLock.lock();
            data.add(System.currentTimeMillis());
            try {
                Thread.sleep(5_000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } finally {
            writeLock.unlock();
        }

    }
    public static void read(){
        try {
            readLock.lock();
            data.forEach(System.out::println);
            try {
                Thread.sleep(5_000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"------");
        } finally {
            readLock.unlock();
        }
    }
    public static void main(String[] args) {
        Thread thread1 = new Thread(()->write());
        thread1.start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Thread thread2 = new Thread(()->read());
        thread2.start();
        Thread thread3 = new Thread(()->read());
        thread3.start();
    }
}
